package com.jiang.action;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jiang.utils.JSONUtil;
import com.jiang.utils.processor.UtilDateProcessor;
import com.jiang.vo.ResultSet;
import com.jiang.vo.TimeFormat;

import net.sf.json.JSONObject;
import net.sf.json.processors.JsonValueProcessor;

public class BaseAction extends HttpServlet {

	private static final long serialVersionUID = -4417238962770449042L;
	public HttpServletRequest request = null;
	public HttpServletResponse response = null;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		this.request = req;
		this.response = resp;
		// 通过反射查找调用的方法
		String uri = req.getRequestURI();
		// 字符串处理就留下最后一个调用的方法
		String methodName = uri.substring(uri.lastIndexOf("/") + 1);
		// 利用反射调用方法
		try {
			Method method = this.getClass().getDeclaredMethod(methodName);
			ResultSet rs = (ResultSet) method.invoke(this);
			// 使用增加转换器(装潢模式)的JSONObject返回
	        // 定义一个类型转化器集合，键是需要转换的类型全路径，值是用于转换的类型转换器  
	        Map<String, JsonValueProcessor> processors = new HashMap<String, JsonValueProcessor>();  
	        //有了2-3种时间转换器，那么我们设计时，就可以短时间格式用Date,长时间格式就是用Timestamp  
	        processors.put("java.util.Date", new UtilDateProcessor(TimeFormat.SHORTFORMAT));  
			// 利用JSON直接返回
			JSONObject jsonObj = JSONUtil.toJson(rs, processors);
			// 利用respose返回JSON给客户端
			this.response.getWriter().println(jsonObj);

		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

	}

}
